#!/usr/bin/perl
#
# tabulate some entries in tab-separated format, one per line
#
# Arguments: filename field...
#

use POSIX;
use FileTable;

$maxcount = 9999999; # 10 million approx = infinity
$usage = "Usage: $0 [-max n] filename [field...]\n";

while ($ARGV[0] =~ /^-/) {
    $opt = shift;
    if ($opt eq "-max") {
	$maxcount = shift;
    } else {
	die $usage;
    }
}

$filename = shift;
die $usage if !$filename;
@fields = @ARGV;
$file = FileTable::open("$filename");
die $usage if !$file;
if ($#fields == -1) {
    print STDERR "Using all user fields\n";
    @fields = $file->fields();
}
	

die "Unable to open DB $filename\n" if !$file;
print "#key";
for $field (@fields) {
    # add an @ to get this always alpha-sorted first
    print "\t\@$field";
}
print "\n";
for $field (@fields) {
    if ($field =~ /\/raw$/) {
	$raw = 1;
    }
}


while ($key = $file->each) {
    last if $reccount >= $maxcount;
    $rec = $file->getclean($key);
    if ($raw) {
	$rawrec = $file->get($key);
    }
    $txt = $key;
    for $field (@fields) {
	$txt .= "\t";
	if ($field =~ /\/raw$/) {
	    $txt .= $rawrec->{$`};
	} else {
	    $txt .= $rec->{$field};
	}
    }
    print $txt, "\n";
    ++ $reccount;
    if ($reccount % 100 == 0 && -t STDERR) {
	print STDERR "$reccount\r";
    }
}
print STDERR "$reccount records counted\n";

    
